package controller;

import com.alibaba.fastjson.JSON;
import dao.Dorm_roomsDao;
import service.Dorm_bedsService;
import service.Dorm_roomsService;
import service.impl.Dorm_bedsServiceimpl;
import service.impl.Dorm_roomsServiceimpl;
import vo.Student_checkin;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/Dorm_bedsController")
public class Dorm_bedsController extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        Dorm_bedsService dor = new Dorm_bedsServiceimpl();
        HttpSession session = req.getSession(true);
        String op = req.getParameter("op");
        PrintWriter out = resp.getWriter();
        if (op.equals("add")) {
            Dorm_roomsService dro2 = new Dorm_roomsServiceimpl();
            String roomid = req.getParameter("roomid");
            String name = req.getParameter("name");
            String stuid = req.getParameter("student");
            int i = 0;
            try {
                i = dor.add(Integer.parseInt(roomid), name, Integer.parseInt(stuid));
                if (i > 0) {
                    out.write("分配床位成功");
                } else {
                    out.write("分配床位失败");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

        }else if(op.equals("cx")){
            Dorm_bedsService ds=new Dorm_bedsServiceimpl();
            String room=req.getParameter("room_id");
            String bed=req.getParameter("bed_number");
            try {
                List<Student_checkin>  list =  ds.cx(Integer.parseInt(room),bed);
                out.write(JSON.toJSONString(list.size()>0?list.get(0).getStudent_number():null));
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
